package ch.jhc.sevlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.dbutils.QueryRunner;

import ch.jhc.Global;
import ch.jhc.bean.Article;
import ch.jhc.db.ArticleDao;

@WebServlet("/list.do")
public class ListMyServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	//需要的数据：1.当前页码  通过参数page=  当前用户提供;
	//2.总页数;
	//3.文章列表

	protected void doGet(HttpServletRequest request,HttpServletResponse response)
			throws ServletException, IOException{
		
		String type = request.getParameter("type");
		if(type == null) {
			type = "html";
		}
		
		String pageNum = request.getParameter("page");
		//当前页数
		int currentPage = 0 ;
		if (pageNum != null) {
			try {
				currentPage = Integer.valueOf(pageNum).intValue();
			} catch (NumberFormatException e1) {
				// TODO: handle exception
				e1.printStackTrace();
				currentPage = 0 ;
			}
		}
		
		
		QueryRunner runner = (QueryRunner) request.getServletContext().getAttribute(Global.KEY_QUERY_RUNNER);
		List<Article> articles = null;
		
		long count = 0;
		
		try {
			articles = ArticleDao.find(runner, currentPage);
			count = ArticleDao.count(runner);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		long total = count % Global.PAGE_SIZE == 0? count /Global.PAGE_SIZE: count /Global.PAGE_SIZE + 1;
		
		if (type.equals("html")) {
		//两种解决方案：
		//一是session + redirect   回收不了的               两次来回请求，会在新的地址发一个请求
		//request.getSession().setAttribute("articles", articles);
		//response.sendRedirect("./list.jsp");
		
		// 二是request + forward   生命周期很短 请求来请求去 完成后就没有了         forward 在服务器内部跳转  可以一直jsp传下去 
		request.setAttribute("articles", articles);
		request.setAttribute("currentPage", currentPage);
		request.setAttribute("total", total);
		request.getRequestDispatcher("./wode.jsp").forward(request, response);
		}else if(type.equals("json")){
			response.setContentType("application/json; charset=utf8");
			JsonArrayBuilder builder = Json.createArrayBuilder();
			for(Article article : articles) {
				builder.add(article.toJson());
			}
			/*JsonValue jValue = Json.createObjectBuilder()
					.add("articles", builder)
					.add("currentPage", currentPage)
					.add("total", total)
					.build();*/
			PrintWriter writer = response.getWriter();
			writer.print(builder.build().toString());
		}
	}
}
